package com.xframe.common.core.interceptor;

import com.xframe.domain.CredentialsContainer;
import com.xframe.domain.EmpUserCredentials;
import com.xframe.domain.role.IUserCredentials;
import com.xframe.common.core.service.login.ITokenService;
import com.xframe.common.core.service.login.TokenServiceFactory;
import com.xframe.xdal.core.util.StringUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Log4j2
//@Component
public class CredentialsInterceptor implements HandlerInterceptor {

    public static final String TOKEN_NAME = "Authorization";

    final String NullFlag = "undefined";

    @Value("${login.expirationTime}")
    private Integer expirationTime = 1800;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String serPath = request.getServletPath();
        String contextPath = request.getServletContext().getContextPath();
        log.info("contextPath = {}",contextPath);
        String userToken = request.getHeader(TOKEN_NAME);
        log.info("Authorization = {}",userToken);
        if(StringUtil.isNotEmpty(userToken) && !StringUtil.equals(NullFlag,userToken) ) {
            ITokenService tokenService = TokenServiceFactory.create();
            IUserCredentials userCredentials = tokenService.getUserCredentials(userToken, EmpUserCredentials.class,false);
            if(userCredentials != null){
                CredentialsContainer.addCredentials(userCredentials);
                tokenService.updateUserCredentials(userToken,userCredentials,expirationTime);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CredentialsContainer.remove();
    }
}
